﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VideoClips.WinUI.Common;
using VideoClips.WinUI.Models;

namespace VideoClips.WinUI.Forms
{
    public partial class FrmBatchMain : Form
    {
        public FrmBatchMain()
        {
            InitializeComponent();
        }

        private void FrmBatchMain_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;

            //txtOutputPath.Text = Path.Combine(Environment.CurrentDirectory, "output");
            //lblCurPath.Text = Path.Combine(Environment.CurrentDirectory, "input");
            txtOutputPath.Text = Environment.CurrentDirectory;
            lblCurPath.Text = Environment.CurrentDirectory;

            if (Directory.Exists(lblCurPath.Text))
            {
                List<string> videoFiles = GetVideoFiles(lblCurPath.Text);
                dataGridView1.DataSource = videoFiles.Select(f => new Video { FileName = Path.GetFileName(f), FilePath = f }).ToList();
            };       
        
        }

        private void FrmBatchMain_DragDrop(object sender, DragEventArgs e)
        {
            //string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            //string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            //if (Directory.Exists(files[0]))
            //{
            //    textBox1.Text = files[0];
            //}
        }

        private void FrmBatchMain_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (Directory.Exists(files[0]))
                {
                    string folderPath = files[0];
                    lblCurPath.Text = folderPath;
                    List<string> videoFiles = GetVideoFiles(folderPath);
                    dataGridView1.DataSource = videoFiles.Select(f => new Video { FileName = Path.GetFileName(f), FilePath = f }).ToList();
                    //e.Effect = DragDropEffects.None;
                }
                else
                {
                    //e.Effect = DragDropEffects.None;
                }
                e.Effect = DragDropEffects.None;
            }
            //if (e.Data.GetDataPresent(DataFormats.FileDrop))
            //    e.Effect = DragDropEffects.Link;                                                              //重要代码：表明是所有类型的数据，比如文件路径
            //else
            //    e.Effect = DragDropEffects.None;
        }
       
        
    
        private void btnSelectPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.SelectedPath=Environment.CurrentDirectory;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string folderPath = folderBrowserDialog.SelectedPath;
                lblCurPath.Text= folderPath;
                List<string> videoFiles = GetVideoFiles(folderPath);
                dataGridView1.DataSource = videoFiles.Select(f => new Video{ FileName = Path.GetFileName(f), FilePath = f }).ToList();
            }
        }

        private List<string> GetVideoFiles(string folderPath)
        {
            List<string> videoFiles = new List<string>();
            //string[] fileExtensions = { ".mp4", ".avi", ".mkv", ".wmv" };
            string[] fileExtensions = { ".mp4"};
            foreach (string file in Directory.GetFiles(folderPath))
            {
                if (fileExtensions.Contains(Path.GetExtension(file)))
                {
                    videoFiles.Add(file);
                }
            }
            if (cbCanSubDir.Checked)
            {
                foreach (string subFolder in Directory.GetDirectories(folderPath))
                {
                    videoFiles.AddRange(GetVideoFiles(subFolder));
                }
            }           
            return videoFiles;
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
        }
      
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dataGridView1.RowHeadersWidth - 4, e.RowBounds.Height);
            //TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle,
            //dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void btnSelectOutput_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.SelectedPath = Environment.CurrentDirectory;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
               txtOutputPath.Text = folderBrowserDialog.SelectedPath;
            }
        }

       
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(lblCurPath.Text))
            {
                List<string> videoFiles = GetVideoFiles(lblCurPath.Text);
                dataGridView1.DataSource = videoFiles.Select(f => new Video { FileName = Path.GetFileName(f), FilePath = f }).ToList();
            };
        }

        private void btnBegin_Click(object sender, EventArgs e)
        {

            // 判断生成目录是否存在
            if (!Directory.Exists(txtOutputPath.Text))
            {
                MessageBox.Show("请选择正确的视频输出路径");
                return;
            }
            //获取所有选中的行
            List<Video> selVideos = ((List<Video>)dataGridView1.DataSource).Where(v=>v.IsChecked==true).ToList();
            if (selVideos.Count == 0)
            {
                MessageBox.Show("请勾选要处理的视频");
                return;
            }

            //处理视频
            for(int i=0;i<selVideos.Count; i++)
            {
                lblStatus.Text = "正在处理第"+(i+1)+"个视频...";
                RunFFEGPH(selVideos[i].FileName, selVideos[i].FilePath);
            }
            lblStatus.Text = selVideos.Count+"个视频全部处理结束";

        }

        private void RunFFEGPH(string fileName,string filePath)
        {            
            string strCmd = "-i " + filePath;
            //–i input –vcodeccopy –an output.avi";            
            //采用截取时
            if (cbClipSub.Checked)
            {
                string startTime = txtClipSubBegin.Text.Trim();
                strCmd += " -ss " + startTime;

                double clipLength = double.Parse(txtClipSubLength.Text.Trim());
                strCmd += " -t " + clipLength;
            }
            else 
            {
                if (cbClipBegin.Checked)
                {
                    string startTime = txtClipBegin.Text.Trim();
                    strCmd += " -ss " + startTime;
                };
                if (cbClipEnd.Checked)
                {
                    double duration = FFMEPGHelper.GetVideoDuration(filePath);
                    double clipEnd = double.Parse(txtClipEnd.Text.Trim());
                    strCmd += " -to " + (duration - clipEnd);
                };
            };

            if (cbCrf.Checked)
            {
                strCmd += " -crf " + txtCrf.Text.Trim();
            }
            if (cbReverse.Checked)
            {
                //strCmd += "  -vf reverse -af areverse";
                strCmd += "  -vf reverse";
            }

            string fileNameNum = fileName.Replace(".mp4","_"+DateTime.Now.ToString("yyyyMMdd")+".mp4") ;
            string dstFile=Path.Combine(txtOutputPath.Text, fileNameNum);
            //strCmd += " -vcodec copy -acodec copy " + dstFile + " -y ";
            strCmd += " " + dstFile + " -y ";
            //
            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.Arguments = strCmd;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            process.WaitForExit();
        }


        private void getVideoDuration(string videoPath)
        {
            string ext = Path.GetExtension(videoPath);
            string ffprobe_cmd = $"ffprobe -i {videoPath} -show_entries format=duration -v quiet -of csv=\"p=0\"";
        }     
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                dataGridView1.ReadOnly = true;
                string val = dataGridView1.Columns[0].HeaderText;
                List<Video> videos = (List<Video>)dataGridView1.DataSource;
                if (val.Equals("全选"))
                {
                    dataGridView1.Columns[0].HeaderText = "取消";
                                       
                    for (int i = videos.Count - 1; i >= 0; i--)
                    {
                        videos[i].IsChecked = true;
                    }
                    //修改后要刷新一下表格,否则可能数据变更界面显示会有延时
                    dataGridView1.Refresh();
                }
                else
                {
                    dataGridView1.Columns[0].HeaderText = "全选";
                    for (int i = videos.Count - 1; i >= 0; i--)
                    {
                        videos[i].IsChecked = false;
                    }
                    dataGridView1.Refresh();
                }
                dataGridView1.ReadOnly = false;
            }
        }

        private void cbClipSub_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb=(CheckBox)sender;
            if (cb.Name== "cbClipSub")
            {
                if (cb.Checked)
                {
                    cbClipBegin.Checked = false;
                    cbClipEnd.Checked = false;
                }               
            }
            else if (cb.Name == "cbClipBegin")
            {
                if (cb.Checked)
                {
                    cbClipSub.Checked = false;
                }
            }
            else if (cb.Name == "cbClipEnd")
            {
                if (cb.Checked)
                {
                    cbClipSub.Checked = false;
                }
            }
        }
    }
}
